<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Jobs\DelAttachJob;
use App\Models\AnimalCatMatch;
use App\Models\Circle;
use App\Services\CircleDimSearchService;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class BaiDuController extends BaseController
{

    private function object_detect($file_path, $token) {
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/object_detect?access_token=' . $token;
        $img = file_get_contents($file_path);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img,
            'with_face' => 1
        );
        $res = $this->request_post($url, $bodys);
        $arr = json_decode($res, true);
        return $arr['result'];
    }

    // https://shimo.im/mindmaps/qY6X9qPx3xkxVHXJ
    public function imageClassify(Request $request) {
        $this->validate($request, [
            'longitude' => 'required',
            'latitude' => 'required',
            'city' => 'required',
            'file_path' => 'required',
        ]);
        $arr_circle_id = [];
        $input = $request->input();
        $city = \request('city', get_city_by_position($input));
        $circle = Circle::where('is_area', 1)->where('city', $city)->where('id', '<=', 371)->first();
        $circle && array_push($arr_circle_id, $circle->id);

        $token = $this->accessToken();
        if ($input['file_path'] == 'undefined/undefined') {
            return $this->failed('图片上传失败，麻烦重新上传下图片');
        }
        $file_path = $input['file_path'] . '?imageView2/2/format/jpg';
        $result = $this->object_detect($file_path, $token);
        $img = Image::make($file_path);
        $img = $img->crop($result['width'], $result['height'], $result['left'], $result['top'])->stream('jpg', 100);
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=' . $token;
//        $img = file_get_contents($input['file_path']);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img,
            'baike_num' => 1
        );
        $res = $this->request_post($url, $bodys);
        \Log::info($res);
        $classify = json_decode($res, true);
        $first = $classify['result'][0];
        if (!$first) {
            return $this->failed('请重新上传试下');
        }
        $name = $first['name'];

        $desc = $circle_list = null;
        $score = '';
        if ($name != '非动物') {
            $desc = $first['baike_info']['description'] ?? '';
            $score = $first['score'];
            $txt = $name . $desc;
            //2:判断是否猫狗，排除龙猫
            if (strpos($txt, '猫') !== false) {
                if (strpos($txt, '龙猫') === false) {
                    $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%猫咪%')->where('id', '<=', 3065)->first();
                    $circle && array_push($arr_circle_id, $circle->id);
                }
            } else if ( strpos($txt, '狗') !== false ||  strpos($txt, '犬') !== false ) {
                $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%狗狗%')->where('id', '<=', 3065)->first();
                $circle && array_push($arr_circle_id, $circle->id);
            }

            //3.
            $dim_circle_id = CircleDimSearchService::handle($txt, $name);
            $dim_circle_id && array_push($arr_circle_id, $dim_circle_id);

            $user_id = $this->getUserId();
            $circle_list = Circle::whereIn('id', $arr_circle_id)->withCount(['is_focus' => function($qr) use($user_id){
                $qr->where('user_id', $user_id);
            }])->orderBy(\DB::raw('FIND_IN_SET(id, "' . implode(",", $arr_circle_id) . '"' . ")"))
                ->get();
        }
        AnimalCatMatch::create([
            'title' =>  $name,
            'desc' => $desc,
            'score' => $score,
            'file_path' => $file_path,
            'ip' => get_client_ip(),
            'rec_circle_ids' => implode(",", $arr_circle_id)
        ]);

        $category = $first;//$classify['result'];

//        $this->dispatch(new DelAttachJob($input['file_path']));

        return $this->success(compact('circle_list', 'category'));
    }

    public function matchCircleList(Request $request) {
        $this->validate($request, [
            'longitude' => 'required',
            'latitude' => 'required',
            'city' => 'required',
            'file_path' => 'required',
            'name' => 'required',
            'score' => 'required',
        ]);
        $input = $request->input();
        $name = $request->input('name');
        $desc = $request->input('desc', '');
        $score = $request->input('score', '');
        $file_path = $input['file_path'] . '?imageView2/2/format/jpg';
        $arr_circle_id = [];

        $city = \request('city', get_city_by_position($input));
        $circle = Circle::where('is_area', 1)->where('city', $city)->where('id', '<=', 371)->first();
        $circle && array_push($arr_circle_id, $circle->id);

        $circle_list = null;

        if ($name != '非动物') {
            $txt = $name . $desc;
            //2:判断是否猫狗，排除龙猫
            if (strpos($txt, '猫') !== false) {
                if (strpos($txt, '龙猫') === false) {
                    $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%猫咪%')->where('id', '<=', 3065)->first();
                    $circle && array_push($arr_circle_id, $circle->id);
                }
            } else if ( strpos($txt, '狗') !== false ||  strpos($txt, '犬') !== false ) {
                $circle = Circle::where('is_area', 1)->where('city', $city)->where('title', 'like', '%狗狗%')->where('id', '<=', 3065)->first();
                $circle && array_push($arr_circle_id, $circle->id);
            }

            //3.
            $dim_circle_id = CircleDimSearchService::handle($txt, $name);
            $dim_circle_id && array_push($arr_circle_id, $dim_circle_id);

            $user_id = $this->getUserId();
            $circle_list = Circle::whereIn('id', $arr_circle_id)->withCount(['is_focus' => function($qr) use($user_id){
                $qr->where('user_id', $user_id);
            }])->orderBy(\DB::raw('FIND_IN_SET(id, "' . implode(",", $arr_circle_id) . '"' . ")"))
                ->get();

            AnimalCatMatch::create([
                'title' =>  $name,
                'desc' => $desc,
                'score' => $score,
                'file_path' => $file_path,
                'ip' => get_client_ip(),
                'rec_circle_ids' => implode(",", $arr_circle_id)
            ]);
        }
        return $this->success(compact('circle_list'));
    }

    public function accessToken() {
        return \Cache::remember('baidu_access_token', now()->addDay(20), function () {
            $appid = '23623470';
            $client_id = 'lKLnecELY5Pnn2cAAm1YnNGS';
            $client_secret = 'n8MugDY7MyGCv5dzR73bVrWwtBxBiVpp';

            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $post_data['grant_type']       = 'client_credentials';
            $post_data['client_id']      =  $client_id;
            $post_data['client_secret'] = $client_secret;
            $o = "";
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
            $res = $this->request_post($url, $post_data);
            \Log::info($res);
            $arr = json_decode($res, true);
            return $arr['access_token'];
        });
    }

    function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }

}